package com.rzico.sbl.ui.manager

import android.view.inputmethod.EditorInfo
import android.widget.CompoundButton
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMasterTransferBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.MasterData
import com.rzico.sbl.model.MemberData
import com.rzico.sbl.other.showTransferDialog
import com.rzico.sbl.other.userRole
import com.rzico.sbl.ui.member.MemberDetailActivity
import com.rzico.sbl.viewmodel.MasterViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.ActivityStack
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.setCompoundDrawable
import com.xinnuo.common_ui.utils.subscribeByFinally
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter

class MasterTransferActivity : BaseActivity(R.layout.activity_master_transfer) {

    private val mBinding by lazy { ActivityMasterTransferBinding.bind(getRootView()) }

    private lateinit var mMasterId: String

    // 员工列表
    private val mMemberList = arrayListOf<MasterData>()
    private var mKeyWord = ""

    override fun getViewModel() = get<MasterViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        initLayout()
        initSearch()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding
            .transferAll
            .setCompoundDrawable(
                leftSize = 16f,
                leftDrawable = R.drawable.address_default_selector
            )

        mBinding
            .listLayout
            .apply {
                emptyLayout
                    .also {
                        it.emptyHint.text = "暂无相关会员信息！"
                    }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration())

                    mAdapter = SlimAdapter.creator()
                        .register<MemberData>(R.layout.item_master_transfer) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_transfer_name, bean.name)
                                text(R.id.item_transfer_phone, bean.mobile)
                                text(R.id.item_transfer_adress, bean.address)

                                with<ImageView>(R.id.item_transfer_img) {
                                    it.loadCircleImage(bean.logo, R.mipmap.default_user)
                                }

                                image(
                                    R.id.item_transfer_check,
                                    conditionIf(
                                        bean.check,
                                        R.mipmap.login_yes_orange,
                                        R.mipmap.login_no
                                    )
                                )

                                clicked(R.id.item_transfer_check) {
                                    bean.check = !bean.check
                                    notifyItemChanged(index)

                                    checkAllSelected()
                                }

                                clicked(R.id.item_transfer) {
                                    (userRole in "1,2")
                                        .condition {
                                            startActivityEx<MemberDetailActivity>(
                                                "cardId" to bean.id,
                                                "memberId" to bean.memberId
                                            )
                                        }
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    private fun initSearch() {
        mBinding
            .transferSearch
            .apply {
                searchEdit.hint = "请输入姓名、手机号、地址"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        (it.isEmpty() && mKeyWord.isNotEmpty())
                            .condition {
                                mKeyWord = ""
                                updateList()
                            }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        searchEdit.text.isBlank()
                            .conditionElse(
                                actionTrue = { showToast("请输入姓名、手机号、地址") },
                                actionFalse = {
                                    mKeyWord = searchEdit.textTrim
                                    updateList()
                                }
                            )
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    searchEdit.text.isBlank()
                        .conditionElse(
                            actionTrue = { showToast("请输入姓名、手机号、地址") },
                            actionFalse = {
                                mKeyWord = searchEdit.textTrim
                                updateList()
                            }
                        )
                }
            }
    }

    override fun initListener() {
        mMasterId = intent.getExtra("masterId")

        mBinding.apply {
            transferBottom.isVisible = userRole in "1,2"

            transferAll.oneTouch(handle = { mList.isEmpty() })
            transferAll.setOnCheckedChangeListener(this@MasterTransferActivity)

            transferCancel.oneClick {
                startActivityEx<MasterTransferRecordActivity>()
            }

            transferSure.oneClick {
                mList.notEmpty {
                    when {
                        any { (it as MemberData).check } -> {
                            mMemberList.isEmpty()
                                .conditionElse(
                                    actionTrue = { getMemberList { showConfirmDialog() } },
                                    actionFalse = ::showConfirmDialog
                                )
                        }
                        else -> showToast("请选择要转移的会员")
                    }
                }
            }
        }

        observe<String>("batchList") {
            getViewModel()
                .delay { updateList() }
        }
    }

    /**
     * 全选点击事件监听
     */
    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        mList.forEach { (it as MemberData).check = isChecked }
        mAdapter.notifyDataSetChanged()

        mBinding
            .transferSure
            .text = "会员转移${
            totalCount()
                .run {
                    conditionIf(
                        this > 0,
                        "(${this})",
                        ""
                    )
                }
        }"
    }

    /**
     * 检查全选按钮状态
     */
    private fun checkAllSelected() {
        mBinding.apply {
            transferAll.setOnCheckedChangeListener(null)
            transferAll.isChecked =
                mList.isNotEmpty() and mList.none { !(it as MemberData).check }
            transferAll.setOnCheckedChangeListener(this@MasterTransferActivity)

            transferSure.text = "会员转移${
                totalCount()
                    .run {
                        conditionIf(
                            this > 0,
                            "(${this})",
                            ""
                        )
                    }
            }"
        }
    }

    /**
     * 选中数量
     */
    private fun totalCount() = mList.count { (it as MemberData).check }

    /**
     * 客户转移弹框
     */
    private fun showConfirmDialog() {
        mMemberList.isNotEmpty()
            .conditionElse(
                actionTrue = {
                    showTransferDialog(
                        items = mMemberList.map { data ->
                            "${data.name.orEmpty()}${data.mobile.ifNotEmpty { " $it" }}"
                        },
                        listener = { index, _, memo ->
                            val idList = mList
                                .filter { (it as MemberData).check }
                                .map { (it as MemberData).id }

                            getViewModel()
                                .requestBind(
                                    isMultipart = true,
                                    requestUrl = BaseUrl.mngTrans,
                                    params = arrayOf(
                                        "from" to mMasterId,
                                        "to" to mMemberList[index].id,
                                        "ids" to idList.joinToString(","),
                                        "memo" to memo
                                    )
                                )
                                .bindLifeCycle(getLifecycleOwner())
                                .subscribeBySuccess(
                                    event = getViewModel(),
                                    onSuccess = {
                                        showToast("客户转移成功！")

                                        updateList()

                                        // 更新员工列表
                                        LiveEventBus
                                            .get("masterList")
                                            .post("${idList.size}")

                                        // 关闭员工详情页
                                        ActivityStack
                                            .screenManager
                                            .popActivities(
                                                MasterInfoActivity::class.java
                                            )
                                    }
                                )
                        }
                    )
                },
                actionFalse = { showToast("暂无可转移员工") }
            )
    }

    /**
     * 员工列表
     */
    private fun getMemberList(onFinish: () -> Unit) {
        getViewModel()
            .masterShop(requestUrl = BaseUrl.mngList)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { list ->
                    mMemberList.clear()

                    list.notEmpty {
                        mMemberList.addAll(
                            filter { it.roleId in "1,2,3,10" && it.id != mMasterId }
                        )
                    }

                    onFinish.invoke()
                }
            )
    }

    /**
     * 员工派单列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .masterNamedList(
                page = index,
                keyWord = mKeyWord,
                masterId = mMasterId,
                onSuccess = {
                    mList.apply {
                        (index == 0).condition {
                            clear()
                            pageNum = 0
                        }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    checkAllSelected()

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh
                                .isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 列表数据刷新
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh
                    .isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}